package com.code2roc.jarmanage.servlet.war;

import com.code2roc.jarmanage.db.ProjectDB;
import com.code2roc.jarmanage.db.WarDB;
import com.code2roc.jarmanage.depoly.DepolyPlatform;
import com.code2roc.jarmanage.model.ProjectDO;
import com.code2roc.jarmanage.model.Result;
import com.code2roc.jarmanage.model.WarDO;
import com.code2roc.jarmanage.util.CommonUtil;
import com.code2roc.jarmanage.util.EnviromentUtil;
import com.code2roc.jarmanage.util.FileUtil;
import com.sun.javafx.binding.StringFormatter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;

public class WarInsertSerlvet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        WarDO entity = CommonUtil.getParamEntity(req, WarDO.class);
        entity.setDepolyType("war");
        if (WarDB.checkExistServiceName(entity.getServiceName())) {
            result = Result.errorResult().setMsg("服务名称重复");
            resp.getWriter().println(result.toString());
            return;
        }
        if (WarDB.checkExistDepolyPort(entity.getWarPort())) {
            result = Result.errorResult().setMsg("部署端口重复");
            resp.getWriter().println(result.toString());
            return;
        }
        String jarPath = "depoly-war" + File.separator + entity.getServiceName().trim();
        FileUtil.initfloderPath(jarPath);
        entity.setJarPackagePath(jarPath);
        String webappsPath = "depoly-war" + File.separator + entity.getServiceName().trim() + File.separator + "webapps";
        FileUtil.initfloderPath(webappsPath);
        String depolyBeforeParam = "-Dfile.encoding=UTF-8 ";
        if (!EnviromentUtil.getDepolyPlaform().equals(DepolyPlatform.Windows)) {
            depolyBeforeParam += "-Djava.awt.headless=true";
        }
        entity.setDepolyBeforeParam(depolyBeforeParam);
        String jvmParam = MessageFormat.format("-Xms{0}m -Xmx{1}m {2}", entity.getInitMemorySize(), entity.getMaxMemorySize(), depolyBeforeParam);
        String param = "\"" + entity.getServiceName() + "★" + new File(jarPath).getAbsolutePath() + "★" + entity.getWarPort() + "★" + entity.getContextPath() + "★" + jvmParam + "★" + entity.getSkipScan() + "\"";
        entity.setDepolyAfterParam(param);
        WarDB.insert(entity);
        resp.getWriter().println(result.toString());
    }
}
